<!doctype html>
<html class="no-js" lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>
    
  iOS WKWebView 本地HTML、JS、CSS文件加载详解 - kaelinda
  
  </title>
  
  
  <link href="atom.xml" rel="alternate" title="kaelinda" type="application/atom+xml">
    <link rel="stylesheet" href="asset/css/foundation.min.css" />
    <link rel="stylesheet" href="asset/css/docs.css" />
    <script src="asset/js/vendor/modernizr.js"></script>
    <script src="asset/js/vendor/jquery.js"></script>
  <script src="asset/highlightjs/highlight.pack.js"></script>
  <link href="asset/highlightjs/styles/github.css" media="screen, projection" rel="stylesheet" type="text/css">
  <script>hljs.initHighlightingOnLoad();</script>
<script type="text/javascript">
  function before_search(){
    var searchVal = 'site:kaelinda.top ' + document.getElementById('search_input').value;
    document.getElementById('search_q').value = searchVal;
    return true;
  }
</script>
  </head>
  <body class="antialiased hide-extras">
    
    <div class="marketing off-canvas-wrap" data-offcanvas>
      <div class="inner-wrap">


<nav class="top-bar docs-bar hide-for-small" data-topbar>


  <section class="top-bar-section">
  <div class="row">
      <div style="position: relative;width:100%;"><div style="position: absolute; width:100%;">
        <ul id="main-menu" class="left">
        
        <li id=""><a target="_self" href="index.html">最近更新</a></li>
        
        <li id=""><a target="_self" href="archives.html">归档目录</a></li>
        
        <li id="ios.css"><a target="_self" href="ios.html">iOS</a></li>
        
        <li id="swift.css"><a target="_self" href="swift.html">Swift</a></li>
        
        <li id="reactnative.css"><a target="_self" href="reactnative.html">RN</a></li>
        
        <li id="js.css"><a target="_self" href="js.html">JS</a></li>
        
        <li id="shell.css"><a target="_self" href="shell.html">shell</a></li>
        
        <li id="coding.css"><a target="_self" href="coding.html">编程</a></li>
        
        <li id="live.css"><a target="_self" href="live.html">随笔</a></li>
        
        <li id="app.css"><a target="_blank" href="app.html">APP推荐</a></li>
        
        </ul>

        <ul class="right" id="search-wrap">
          <li>
<form target="_blank" onsubmit="return before_search();" action="http://google.com/search" method="get">
    <input type="hidden" id="search_q" name="q" value="" />
    <input tabindex="1" type="search" id="search_input"  placeholder="Search"/>
</form>
</li>
          </ul>
      </div></div>
  </div>
  </section>

</nav>

        <nav class="tab-bar show-for-small">
  <a href="javascript:void(0)" class="left-off-canvas-toggle menu-icon">
    <span> &nbsp; kaelinda</span>
  </a>
</nav>

<aside class="left-off-canvas-menu">
      <ul class="off-canvas-list">
        
        <li><a target="_self" href="index.html">最近更新</a></li>
        
        <li><a target="_self" href="archives.html">归档目录</a></li>
        
        <li><a target="_self" href="ios.html">iOS</a></li>
        
        <li><a target="_self" href="swift.html">Swift</a></li>
        
        <li><a target="_self" href="reactnative.html">RN</a></li>
        
        <li><a target="_self" href="js.html">JS</a></li>
        
        <li><a target="_self" href="shell.html">shell</a></li>
        
        <li><a target="_self" href="coding.html">编程</a></li>
        
        <li><a target="_self" href="live.html">随笔</a></li>
        
        <li><a target="_blank" href="app.html">APP推荐</a></li>
        

    <li><label>Categories</label></li>

        
            <li><a href="reactnative.html">React-Native</a></li>
        
            <li><a href="ios.html">iOS</a></li>
        
            <li><a href="app.html">MacAPP</a></li>
        
            <li><a href="swift.html">Swift</a></li>
        
            <li><a href="js.html">JavaScript</a></li>
        
            <li><a href="vue.html">Vue</a></li>
        
            <li><a href="shell.html">shell</a></li>
        
            <li><a href="%E7%BD%91%E7%BB%9C.html">网络</a></li>
         

      </ul>
    </aside>

<a class="exit-off-canvas" href="#"></a>


        <section id="main-content" role="main" class="scroll-container">
        
       

 <script type="text/javascript">
  $(function(){
    $('#menu_item_index').addClass('is_active');
  });
</script>
<div class="row">
  <div class="large-8 medium-8 columns">
      <div class="markdown-body article-wrap">
       <div class="article">
          
          <h1>iOS WKWebView 本地HTML、JS、CSS文件加载详解</h1>
     
        <div class="read-more clearfix">
          <span class="date">2017/12/7</span>

          <span>posted in&nbsp;</span> 
          
              <span class="posted-in"><a href='ios.html'>iOS</a></span>
           
         
          <span class="comments">
            

            
          </span>

        </div>
      </div><!-- article -->

      <div class="article-content">
      <blockquote>
<p><strong>Tips:</strong><br/>
NSString类型的文件路径转换为URL的时候，一定要用 <br/>
<code>NSURL *pathURL = [NSURL fileURLWithPath:filePath];</code>方法去转换，否则资源URL不合法，APP会崩溃</p>
</blockquote>

<h2 id="toc_0">上源码接口：</h2>

<h3 id="toc_1">loadRequest方式加载</h3>

<ul>
<li><p>API : iOS8即可使用</p>
<p><code>- (nullable WKNavigation *)loadRequest:(NSURLRequest *)request;</code>      </p></li>
<li><p>用途：</p>
<ul>
<li>1：主要用来加载网络URL<br/></li>
<li>2：也可以加载本地HTML文件（本文重点）</li>
</ul>
<span id="more"></span><!-- more --></li>
</ul>

<h3 id="toc_2">loadFileURL</h3>

<ul>
<li><p>API: URL:文件相对路径 readAccessURL：访问文件需要引用的文件的路径 一般都是比<code>URL</code>大一级或者更高几级</p>
<p><code>- (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL API_AVAILABLE(macosx(10.11), ios(9.0));</code></p></li>
<li><p>用途：主要用于加载本地文件（一般指相对路径）</p></li>
</ul>

<h3 id="toc_3">loadHTMLString</h3>

<ul>
<li><p>API:<br/>
<code>- (nullable WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;</code></p></li>
<li><p>用途：主要用于 HTML转换成的字符串（比如：编程APP）</p></li>
</ul>

<h3 id="toc_4">loadData</h3>

<ul>
<li><p>API: 值得一提的是MIMETType,text/html、image/jpg、text/plain</p>
<p><code>- (nullable WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL API_AVAILABLE(macosx(10.11), ios(9.0));</code></p></li>
<li><p>用途：主要用于加载 二进制状态下的文件，主要包括HTML、Image、Text文本</p></li>
</ul>

<h2 id="toc_5">开发中的HTML文件位置</h2>

<h3 id="toc_6">HTML位于工程内的黄色文件夹下</h3>

<blockquote>
<p>这是咱们一般的文件添加方式，这属于绝对路径的添加</p>
</blockquote>

<p><img src="https://ws4.sinaimg.cn/large/006tNc79ly1fmcxnu043cj313w05maan.jpg" alt="绝对路径"/></p>

<h4 id="toc_7"><strong><code>loadRequest</code> 加载方式</strong></h4>

<blockquote>
<p><strong>Tips:</strong><br/>
 iOS8 的时候只能通过这个<code>loadRequest</code>方法去加载<br/>
iOS8 WKWebView的加载本地文件的方式本文后面会有 <strong>详细方案</strong></p>
</blockquote>

<pre><code class="language-objectiv-c">NSString *bundleStr = [[NSBundle mainBundle] pathForResource:@&quot;feedback&quot; ofType:@&quot;html&quot;];
    
_feedbackUrl = [NSURL fileURLWithPath:bundleStr];
    
[_webview loadRequest:[NSURLRequest requestWithURL:_feedbackUrl]];
</code></pre>

<p><img src="https://ws3.sinaimg.cn/large/006tNc79ly1fmcxsxa56jj30af0j5dgd.jpg" alt="效果"/></p>

<p><strong>warning！！！</strong><br/>
页面能加载出来，但是效果是很差的，因为CSS、JS、图片资源文件没有得到正确的引用！<br/>
那我们该通过什么方式来让这些附属的文件得到正确引用呢？<br/>
iOS9之后新增了 <code>loadFileURL</code> 等一系列加载本地文件的方法</p>

<h4 id="toc_8"><strong><code>loadFileURL</code>加载方式</strong></h4>

<blockquote>
<p>iOS9之后才出现这个加载方式</p>
</blockquote>

<pre><code class="language-objectiv-c">NSString *bundleStr = [[NSBundle mainBundle] pathForResource:@&quot;feedback&quot; ofType:@&quot;html&quot;];
_feedbackUrl = [NSURL fileURLWithPath:bundleStr];
if (@available(iOS 9.0, *)) {
    [_webview loadFileURL:[NSURL fileURLWithPath:bundleStr] allowingReadAccessToURL:[NSURL fileURLWithPath:[NSBundle mainBundle].bundlePath]];
} else {
    // Fallback on earlier versions
}
</code></pre>

<p>哇塞！加载出来了耶！但是 依旧是没能加载其他资源文件啊 😰<br/>
客观，稍安勿躁 ~</p>

<h3 id="toc_9">HTML位于工程内的蓝色文件夹下</h3>

<blockquote>
<p>特殊文件添加方式，尤其是文件之间有相互引用的时候用这种方式</p>
</blockquote>

<p><img src="https://ws2.sinaimg.cn/large/006tNc79ly1fmcxr0jl88j313w05maan.jpg" alt="相对路径添加方式"/></p>

<h4 id="toc_10">loadRequest 方式</h4>

<pre><code class="language-objectiv-c">NSString *filePath = [[NSBundle mainBundle] pathForResource:@&quot;feedback&quot; ofType:@&quot;html&quot; inDirectory:@&quot;FeedbackH5/pages&quot;];
NSURL *pathURL = [NSURL fileURLWithPath:filePath];
if (@available(iOS 9.0, *)) {
    [_webview loadRequest:[NSURLRequest requestWithURL:pathURL]];
}
</code></pre>

<h4 id="toc_11">loadFileURL 方式加载</h4>

<pre><code class="language-objectiv-c">NSString *filePath = [[NSBundle mainBundle] pathForResource:@&quot;feedback&quot; ofType:@&quot;html&quot; inDirectory:@&quot;FeedbackH5/pages&quot;];
    NSURL *pathURL = [NSURL fileURLWithPath:filePath];
    if (@available(iOS 9.0, *)) {
//        [_webview loadRequest:[NSURLRequest requestWithURL:pathURL]];
        [_webview loadFileURL:[NSURL fileURLWithPath:filePath] allowingReadAccessToURL:[NSURL fileURLWithPath:[NSBundle mainBundle].bundlePath]];
    }
</code></pre>

<p><img src="https://ws3.sinaimg.cn/large/006tNc79ly1fmcyc9pjp0j30af0j5wfp.jpg" alt=""/></p>

<blockquote>
<p>由此可见：相对路径方式加载 是可以正常引用JS、css等资源文件的<br/>
但是 iOS 8系统下，依旧加载不出来！！！</p>
</blockquote>

<h3 id="toc_12">HTML位于APP沙盒下Document文件夹</h3>

<blockquote>
<p>iOS8既然添加到工程中引用，一直引用不到，我们可以让他从document路径下引用试试！<br/>
这个方法可以适配 iOS8系统下WKWebView加载本地文件了？<br/>
你还太天真！！！</p>
</blockquote>

<pre><code class="language-objectiv-c">//项目中的文件夹路径
NSString *directoryPath = [KFileManger appSourceName:@&quot;FeedbackH5&quot; andType:@&quot;&quot;];

//沙盒中的document路径
NSString *documentpath = [KFileManger documentPath];
    
//copy文件夹到 document 路径下
[KFileManger copyMissingFile:directoryPath toPath:documentpath];

//document 路径下的HTML文件路径
NSString *homePath = [[KFileManger documentPath] stringByAppendingString:@&quot;/FeedbackH5/pages/feedback.html&quot;];

//document 路径下的HTML文件 URL
NSURL *docSourceURL = [NSURL fileURLWithPath:homePath];
    
[_webview loadRequest:[NSURLRequest requestWithURL:docSourceURL]];
</code></pre>

<blockquote>
<p>果然不出所料(zhe jiu shi wo xiang yao de)，模拟器上能正常加载出界面，图片、CSS但是JS交互是不行的<br/>
在真机 依旧加载不出任何界面！</p>
</blockquote>

<h3 id="toc_13">HTML位于APP沙盒下tmp临时缓存文件夹</h3>

<blockquote>
<p>亲爱的客观们，这才是iOS8系统下加载有相互引用关系的HTML、JS、CSS以及图片资源的正确方法(当前知道的唯一方法如有新的方式私信我哦~)！😊</p>
</blockquote>

<pre><code class="language-objectiv-c">//项目中的文件夹路径
NSString *directoryPath = [KFileManger appSourceName:@&quot;FeedbackH5&quot; andType:@&quot;&quot;];

//tmp缓存文件夹路径
NSString *tmpPath = [KFileManger tmpPath];

//新文件夹名字
NSString *wwwDir =@&quot;www&quot;;

//tmp文件夹下创建www文件夹
[KFileManger createDirWithPath:tmpPath andDirectoryName: wwwDir];

//tmp中的www文件夹中的路径
NSString *tmpWWW = [tmpPath stringByAppendingString: wwwDir];

//copy文件夹到 tmp/www 路径下
[KFileManger copyMissingFile:directoryPath toPath:tmpWWW];

// 字符 tmp/www/FeedbackH5/pages/feedback.html 全路径
NSString *tmpWWWFeedback = [tmpWWW stringByAppendingString:@&quot;/FeedbackH5/pages/feedback.html&quot;];

//tmp 操作，字符转换成URL
NSURL *feedbackURL = [NSURL fileURLWithPath:tmpWWWFeedback];

//WKWebView加载
[_webview loadRequest:[NSURLRequest requestWithURL:feedbackURL]];
</code></pre>


    

      </div>

      <div class="row">
        <div class="large-6 columns">
        <p class="text-left" style="padding:15px 0px;">
      
          <a href="15126628432953.html" 
          title="Previous Post: iOS代码检测入坑记事">&laquo; iOS代码检测入坑记事</a>
      
        </p>
        </div>
        <div class="large-6 columns">
      <p class="text-right" style="padding:15px 0px;">
      
          <a  href="15115332074317.html" 
          title="Next Post: Xcode 代码块">Xcode 代码块 &raquo;</a>
      
      </p>
        </div>
      </div>
      <div class="comments-wrap">
        <div class="share-comments">
          

          

          
        </div>
      </div>
    </div><!-- article-wrap -->
  </div><!-- large 8 -->




 <div class="large-4 medium-4 columns">
  <div class="hide-for-small">
    <div id="sidebar" class="sidebar">
          <div id="site-info" class="site-info">
            
                <div class="site-a-logo"><img src="https://ws1.sinaimg.cn/large/006tNc79ly1fmpk9088gsj30sg0sgn33.jpg" /></div>
            
                <h1>kaelinda</h1>
                <div class="site-des">倘若我心中的山水，你眼中能看到，我便一步一莲花祈祷</div>
                <div class="social">








<a target="_blank" class="twitter" target="_blank" href="https://twitter.com/KaelLVLinda" title="Twitter">Twitter</a>
<a target="_blank" class="github" target="_blank" href="https://github.com/Kaelzzs" title="GitHub">GitHub</a>
<a target="_blank" class="email" href="mailto:zhouzuosong_kael@163.com" title="Email">Email</a>
  <a target="_blank" class="rss" href="atom.xml" title="RSS">RSS</a>
                
              	 </div>
          	</div>

             

              <div id="site-categories" class="side-item ">
                <div class="side-header">
                  <h2>Categories</h2>
                </div>
                <div class="side-content">

      	<p class="cat-list">
        
            <a href="reactnative.html"><strong>React-Native</strong></a>
        
            <a href="ios.html"><strong>iOS</strong></a>
        
            <a href="app.html"><strong>MacAPP</strong></a>
        
            <a href="swift.html"><strong>Swift</strong></a>
        
            <a href="js.html"><strong>JavaScript</strong></a>
        
            <a href="vue.html"><strong>Vue</strong></a>
        
            <a href="shell.html"><strong>shell</strong></a>
        
            <a href="%E7%BD%91%E7%BB%9C.html"><strong>网络</strong></a>
         
        </p>


                </div>
              </div>

              <div id="site-categories" class="side-item">
                <div class="side-header">
                  <h2>Recent Posts</h2>
                </div>
                <div class="side-content">
                <ul class="posts-list">
	      
		      
			      <li class="post">
			        <a href="15523077857608.html">OC中枚举写法  以及 字符串枚举探索</a>
			      </li>
		     
		  
		      
			      <li class="post">
			        <a href="15522686353535.html">iOS 动画全解 (1)</a>
			      </li>
		     
		  
		      
			      <li class="post">
			        <a href="15501356584731.html">UITableView顶部空白的几种解决办法</a>
			      </li>
		     
		  
		      
			      <li class="post">
			        <a href="15488351784332.html">Objective-C中的字符串类型枚举 探索</a>
			      </li>
		     
		  
		      
			      <li class="post">
			        <a href="15409691048860.html">【Swift笔记】引用计数</a>
			      </li>
		     
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		  
		      
		   
		  		</ul>
                </div>
              </div>
        </div><!-- sidebar -->
      </div><!-- hide for small -->
</div><!-- large 4 -->

</div><!-- row -->

 <div class="page-bottom clearfix">
  <div class="row">
   <p class="copyright">Copyright &copy; 2015
Powered by <a target="_blank" href="http://www.mweb.im">MWeb</a>,&nbsp; 
Theme used <a target="_blank" href="http://github.com">GitHub CSS</a>.</p>
  </div>
</div>

        </section>
      </div>
    </div>

  
    

    <script src="asset/js/foundation.min.js"></script>
    <script>
      $(document).foundation();
      function fixSidebarHeight(){
        var w1 = $('.markdown-body').height();
          var w2 = $('#sidebar').height();
          if (w1 > w2) { $('#sidebar').height(w1); };
      }
      $(function(){
        fixSidebarHeight();
      })
      $(window).load(function(){
          fixSidebarHeight();
      });
     
    </script>

    
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script><script type="text/x-mathjax-config">MathJax.Hub.Config({TeX: { equationNumbers: { autoNumber: "AMS" } }});</script>


  </body>
</html>
